const readEnv = require('./readEnv')
const path = require('path')
const env = readEnv('./.env');
const fs = require('fs')

function createConfig(config, configName) {
  try {
    const windowConf = `window.${configName}`
    // Ensure that the variable will not be modified
    const configStr = `${windowConf}=${JSON.stringify(config)};
      Object.freeze(${windowConf});
      Object.defineProperty(window, "${configName}", {
        configurable: false,
        writable: false,
      });
    `.replace(/\s/g, '')
    fs.writeFileSync(path.resolve(__dirname, './lib/app.config.js'), configStr)
  } catch(err) {
    console.log(err)
  }
}
function createScriptLabel() {
  const htmlContent = fs.readFileSync(path.resolve(__dirname, './lib/index.html'), 'utf-8')
  const newHtmlContent = htmlContent.replace('</head>', '<script src="./app.config.js"></script></head>')
  fs.writeFileSync(path.resolve(__dirname, './lib/index.html'), newHtmlContent)
}
createConfig(env, 'GLOBAL_CONFIG')
createScriptLabel()